<?php

class PagesController extends Zend_Controller_Action {

    public function preDispatch() {
        $session = new Zend_Session_Namespace('UnCMS');
        if (!isset($session->acl->pages) || USER_ID == 0)
            $this->_redirect(SITE_URL);
        $t = Zend_Registry::get('Zend_Locale');
        $this->view->navigation_line = array($t->_('Pages') => ADMIN_URL . '/pages');
        if ($this->getRequest()->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        }
    }

    /**
     * Дерево страниц
     */
    public function indexAction() {
        $model = new PageModel();
        $this->view->pages = $model->getPagesTree(true);
    }

    /**
     * Перемещение страницы
     */
    public function flyAction() {
        $id = (int) $this->getRequest()->getparam('id'); //Двигаемая
        $cid = (int) $this->getRequest()->getparam('cid'); //Нижняя
        $model = new PageModel();
        $pages_tree = Zend_Registry::get('pages');
        if (!isset($pages_tree[$id]->acl) || $pages_tree[$id]->acl < 3) {
            $this->_forward('index', 'pages');
        } else {
            $model->flyPage($id, $cid);
            $this->_forward('index', 'pages');
        }
    }

    /**
     * Управление секциями по блокам
     */
    public function sectionAction() {

        $model = new PageModel();
        $forms = new PageForm();
        $pid = (int) $this->getRequest()->getParam('id');

        /*
         * Acl only editors
         */
        $pages_tree = Zend_Registry::get('pages');
        if ($pages_tree[$pid]->acl < 2)
            $this->_redirect('/pages');
        define('PAGE_ID', $pid);
        $this->view->view_page_url = $pages_tree[$pid]['url'];
        $form = $forms->AddSection(array('id' => $pid));
        $this->view->form = $form;
        $this->view->sections = $model->getSections($pid);
        $this->view->blocks = $model->getBlocks($pid);
        $this->view->mods = $model->getAddonsList('page');
        $this->view->modules = $model->getAddonsList('page', 'title');
        $this->view->modsacl = $model->getModulesList();
        $this->view->page = $model->getPages($pid);
        $this->view->navigation_line = $this->view->navigation_line + array($this->view->page->name => ADMIN_URL . '/pages/section/id/' . $pid);
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                array_pop($formData);
                $formData['pid'] = $pid;
                $sid = $model->addSection($formData);
                $module = $model->getAddons('page', $formData['mid']);
                $this->_forward('add', $module->title, 'default', array('sid' => $sid, 'pid' => $pid));
            } else {
                $form->populate($formData);
            }
        }
    }

    /**
     * Свойства секции
     */
    public function settingsAction() {
        $model = new PageModel();
        $forms = new PageForm();
        $sid = (int) $this->getRequest()->getParam('id');

        //Назначаем просмотр страницы для навигации
        $this->view->section = $model->getSection($sid);
        $t = Zend_Registry::get('Zend_Locale');
        /*
         * Acl only editors
         */
        $pages_tree = Zend_Registry::get('pages');
        if ($pages_tree[$this->view->section->pid]->acl < 2)
            $this->_redirect('/pages');

        $this->view->view_page_url = $pages_tree[$this->view->section->pid]['url'];

        $form = $forms->EditSection(array('id' => $sid, 'pid' => $this->view->section->pid, 'mid' => $this->view->section->mid));
        $this->view->form = $form;
        $this->view->page = $model->getPages($this->view->section->pid);
        $this->view->navigation_line = $this->view->navigation_line + array(
            $this->view->page->name => ADMIN_URL . '/pages/section/id/' . $this->view->page->id,
            $this->view->section->name => ADMIN_URL . '/pages/modify/id/' . $this->view->section->id,
            $t->_('Settings') => ADMIN_URL . '/pages/settings/id/' . $this->view->section->id
        );
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                array_pop($formData);
                $formData['id'] = $sid;
                $model->updateSection($formData, $sid);
                if ($sid == 0) {
                    $model->moveSection($sid, 'last');
                }
                $this->_redirect('/pages/section/id/' . $this->view->section->pid);
            } else {
                $form->populate($formData);
            }
        } else {
            $form->populate((array) $this->view->section);
        }
    }

    /**
     * Настройки страницы
     */
    public function editAction() {
        $t = Zend_Registry::get('Zend_Locale');
        $model = new PageModel();
        $forms = new PageForm();
        $pid = (int) $this->getRequest()->getParam('id', 0);
        $link = (int) $this->getRequest()->getParam('link', 0);
        $pages_tree = Zend_Registry::get('pages');
        if ($pid > 0) {
            if ($pages_tree[$pid]->acl < 2)
                $this->_redirect('/pages');
            $this->view->view_page_url = $pages_tree[$pid]['url'];
        }
        $this->view->page = $model->getPages($pid);

        if ($link <> 1) {
            $form = $forms->Page(array('id' => $pid));
        } else {
            $form = $forms->Link(array('id' => $pid));
        }
        
        $this->view->form = $form;
        //Назначаем просмотр страницы для навигации
        if ($pid > 0) {
            $this->view->navigation_line = $this->view->navigation_line + array(
                $this->view->page->name => ADMIN_URL . '/pages/section/id/' . $pid,
                $t->_('Settings') => ADMIN_URL . '/pages/edit/id/' . $pid
            );
        } else {
            if ($link <> 0) {
                $this->view->navigation_line = $this->view->navigation_line + array(
                    $t->_('New link') => ADMIN_URL . '/pages/edit/link/1'
                );   
            } else {
                $this->view->navigation_line = $this->view->navigation_line + array(
                    $t->_('New link') => ADMIN_URL . '/pages/edit/'
                );   
            }

        }
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {
                array_pop($formData);
                /*
                 * В качестве родителя можно выбрать только страницу с правами для редактирования
                 */
                if (isset($pages_tree[$formData['parent']]) && $pages_tree[$formData['parent']]->acl < 2)
                    $this->_redirect('/pages');

                if ($pid == 0) {
                    $auth = Zend_Auth::getInstance();
                    $formData['aid'] = $auth->getIdentity()->id;
                    if ($link == 0) {
                        $pid = $model->updatePage($formData, $pid);
                        $this->_redirect('/pages/section/id/' . $pid);
                    } else {
                        $formData['visible'] = -1;
                        $pid = $model->updatePage($formData, $pid);
                        $this->_redirect('/pages');
                    }
                } else { 
                    if ($formData['parent'] <> $this->view->page->parent) {
                        $moved = true;
                    }
                    if ($link <> 0)
                        $formData['visible'] = -1;

                    $pid = $model->updatePage($formData, $pid);
                    $this->_redirect('/pages');
                }
            } else {
                $form->populate($formData);
            }
        }
        if ($pid > 0) {
            $form->populate($model->getPages($pid, 1));
        }
    }

    /**
     * Перемещение страниц либо секции
     */
    public function moveAction() {
        $model = new PageModel();
        $pid = (int) $this->getRequest()->getParam('id', 0);
        $sid = (int) $this->getRequest()->getParam('sid', 0);

        $action = $this->getRequest()->getParam('position', 0);
        if ($sid > 0) {
            $model->moveSection($sid, $action);
            $this->_redirect('/pages/section/id/' . $pid);
        } else if ($pid > 0) {
            /* /
             * Acl only administrators
             */
            $pages_tree = Zend_Registry::get('pages');
            if ($pages_tree[$pid]->acl < 3)
                $this->_redirect('/pages');

            $model->movePage($pid, $action);
            $this->_redirect('/pages/');
        }
    }

    /**
     * Удаление страницы или секции
     */
    public function deleteAction() {
        $pages_tree = Zend_Registry::get('pages');
        $model = new PageModel();
        $pid = (int) $this->getRequest()->getParam('id', 0);
        $sid = (int) $this->getRequest()->getParam('sid', 0);
        $aclModel = new AclModel();
        if ($pid > 0) { //Удаляем полность страницу
            if ($pages_tree[$pid]->acl < 3)
                $this->_redirect('/pages');
            define('PAGE_ID', $pid);
            $pages = $model->getChilds($pid);
            foreach ($pages as $k => $v) {//Проходим по дочерним страницам и родителю
                $sections = $model->getSections($v->id);
                foreach ($sections as $key => $val) {//Проходим по секциям страницы
                    $sid = $val->id;
                    $model->deleteSection($sid);
                }
                $model->deletePage($v->id);
                $aclModel->updateAcls('pages', $v->id);

                //Удаляем поисковый индекс
                if ($this->view->config->etrace == 0) {
                    $index = Zend_Search_Lucene::open(APP_PATH . '/index');
                    $hits = $index->find('page_id:' . $v->id);
                    foreach ($hits as $hit)
                        $index->delete($hit->id);
                }
            }

            $this->_redirect('/pages/');
        } else if ($sid > 0) {//Удаляем полностью секцию
            $section = $model->getSection($sid);
            $pid = $section->pid;
            if ($pages_tree[$pid]->acl < 3)
                $this->_redirect('/pages');
            $model->deleteSection($sid);
            $this->_redirect('/pages/section/id/' . $pid);
        }
    }

    /**
     * Редактирование секции
     */
    public function modifyAction() {
        $t = Zend_Registry::get('Zend_Locale');
        $model = new PageModel();
        $sid = (int) $this->getRequest()->getParam('id', 0);
        $section = $model->getSection($sid);
        $module = $model->getAddons('page', $section->mid);

        /*
         * Проверяем права на модуль
         */
        $session = new Zend_Session_Namespace('UnCMS');
        if (!isset($session->acl->{$module->title}) && USER_ID <> 1)
            $this->_redirect(SITE_URL);

        $page = $model->getPages($section->pid);

        $pages_tree = Zend_Registry::get('pages');
        if ($pages_tree[$page->id]->acl < 2)
            $this->_redirect('/pages');

        //Назначаем просмотр страницы для навигации
        $this->view->view_page_url = $pages_tree[$section->pid]['url'];

        $this->view->navigation_line = $this->view->navigation_line + array(
            $page->name => ADMIN_URL . '/pages/section/id/' . $page->id,
            $t->_('Section') . ' &laquo;' . $section->name . '&raquo;' => ADMIN_URL . '/pages/modify/id/' . $section->id
        );
        $this->view->section = $section;
        $this->view->page = $model->getPages($section->pid);
        $this->view->module = $module;
        define('PAGE_ID', $section->pid);
        $this->view->setScriptPath(APP_PATH . '/templates/default/scripts');
        $model->updateTime($page->id);

        //Удаляем поисковый индекс
        if ($this->view->config->etrace == 0) {
            $index = Zend_Search_Lucene::open(APP_PATH . '/index');
            $hits = $index->find('page_url:' . $this->view->view_page_url);
            foreach ($hits as $hit)
                $index->delete($hit->id);
        }


        $this->_forward('modify', $module->title, 'default', array('sid' => $sid));
    }

    public function linksAction() {
        $this->_helper->layout()->disableLayout();
        $model = new PageModel();
        $pages = $model->getPagesList();
        echo 'var tinyMCELinkList = new Array(';
        $first = true;
        foreach ($pages as $key => $value) {
            if ($first) {
                $first = false;
            } else {
                echo ',';
            }
            echo '["' . $value . '", "{{{PAGE_' . $key . '}}}"]';
        }
        echo ');';
    }

}
